"""
Runs the game over the network. Currently hardcoded to connect over localhost, with
the host using army1 and the joining player using army2
Utilizes a non-blocking receive in order to keep drawing while waiting for network
input.
"""
import pygame, random, sys, math, Utility, time, Skills, copy, socket, pickle, pdb
from pygame.locals import *
from Unit import *
from Player import *
from Constants import *

def play(windowSurface, assets, type):
    grass = pygame.image.load("images/Grass.png")
    rock = pygame.image.load("images/Rock.png")
    
    units = assets["units"]
    images = assets["images"]
    mainClock = assets["clock"]
    
    #hard code some players
    player1 = Player("Locke", BLUE)
    player2 = Player("Plato", GREEN)
    
    if type == "host":
        host = ''
        port = 50000
        backlog = 5
        size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host,port))
        s.listen(backlog)
        client, address = s.accept()
        
        file = open("armies/p1army.dat", "r")
        army1 = file.readline()
        client.send(army1)
        army2 = client.recv(4096)
        
    else:
        host = 'localhost'
        port = 50000
        size = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host,port))
        
        army1 = s.recv(4096)
        file = open("armies/p2army.dat", "r")
        army2 = file.readline()
        s.send(army2)
        
    army1 = army1.split(" ")
    army2 = army2.split(" ")
    
    for i in range(len(army1)):
            for j in range(len(units)):
                if army1[i] == units[j].name:
                    rect = pygame.Rect(-100,-100,50,50)
                    player1.units.append((copy.copy(units[j]), rect, images[j]))
    for i in range(len(army2)):
            for j in range(len(units)):
                if army2[i] == units[j].name:
                    rect = pygame.Rect(-100,-100,50,50)
                    player2.units.append((copy.copy(units[j]), rect, images[j]))
    
    #set up fonts
    basicFont = pygame.font.SysFont(None, 16)
    midFont = pygame.font.SysFont(None, 32)
    bigFont = pygame.font.SysFont(None, 48)
    gameOver = pygame.font.SysFont(None, 96)
    
    border = pygame.Rect(0,0,50,50)
    
    players = [player1, player2]
    
    #hard code some obstacles
    obstacles = []
    
    obstacles.append(pygame.Rect(300,400,50,50))
    obstacles.append(pygame.Rect(350,350,50,50))
    obstacles.append(pygame.Rect(350,300,50,50))
    obstacles.append(pygame.Rect(350,250,50,50))
    obstacles.append(pygame.Rect(350,200,50,50))
    obstacles.append(pygame.Rect(350,150,50,50))
    obstacles.append(pygame.Rect(250,350,50,50))
    obstacles.append(pygame.Rect(400,100,50,50))
    obstacles.append(pygame.Rect(450,150,50,50))
    
    #build an 2D list of the obstacles for the helper function
    toCheck = [[0]*(FIELDWIDTH//50) for x in range(FIELDHEIGHT//50)]
    for o in obstacles:
        toCheck[o.top//50][o.left//50] = 1
    
    #create a list of vertices that shouldn't be see-through.
    #Given the current line of sight calculation, two diagonal obstacles
    #can be seen through the point where they meet.
    blockedVertices = []
    for i in range(0,FIELDWIDTH,50):
        for j in range(0, FIELDHEIGHT, 50):
            NE = (i+1, j-1)
            NW = (i-1, j-1)
            SE = (i+1, j+1)
            SW = (i-1, j+1)
            NEBlock = NWBlock = SEBlock = SWBlock = False
            for o in obstacles:
                NEBlock = o.collidepoint(NE) or NEBlock
                NWBlock = o.collidepoint(NW) or NWBlock
                SEBlock = o.collidepoint(SE) or SEBlock
                SWBlock = o.collidepoint(SW) or SWBlock
                            
            if (NEBlock and SWBlock) or (NWBlock and SEBlock):
                blockedVertices.append((i,j))
    
    #create the grass background
    ground = pygame.Surface((FIELDWIDTH, FIELDHEIGHT))
    for i in range(0,FIELDHEIGHT,GRIDSIZE):
        for j in range(0,FIELDWIDTH,GRIDSIZE):
            ground.blit(grass, (j,i))
    
    gameState = dict()
    gameState["players"] = players
    gameState["obstacles"] = obstacles
    gameState["blockedVertices"] = blockedVertices
    gameState["grid"] = toCheck
    
    #create rects for the info pane
    infoPane = pygame.Rect(FIELDWIDTH, 0, INFOWIDTH, INFOHEIGHT)
    unitIcon = pygame.Rect(0, 0, 50, 50)
    unitIcon.centerx = infoPane.centerx
    unitIcon.centery = 100
    skillText = midFont.render("Use Skill", True, WHITE, GRAY)
    skillRect = skillText.get_rect()
    skillRect.centerx = infoPane.centerx
    skillRect.top = 300
    
    #start off with the first player
    currentPlayer = players[0]
    currentUnit = None
    
    playerIndex = 0
    unitIndex = 0
    unitSelected = False
    ability = False
    unitHovered = False
    hoveredUnit = None
    
    #draw the grid
    def drawLines():
        for i in range(FIELDWIDTH // GRIDSIZE):
            pygame.draw.line(windowSurface, BLACK, (i*GRIDSIZE,0), (i*GRIDSIZE, FIELDHEIGHT))
                
        for i in range(FIELDHEIGHT // GRIDSIZE):
            pygame.draw.line(windowSurface, BLACK, (0,i*GRIDSIZE), (FIELDWIDTH, i*GRIDSIZE))
    
    #draw battle results
    def drawResult(target, a, d):
        result = midFont.render(str(a)+" v "+str(d)+" ",True, BLACK)
        resultBack = pygame.Rect(0, 0, result.get_width(), result.get_height())
        resultBack.centerx = target[1].centerx
        resultBack.bottom = target[1].top
        pygame.draw.rect(windowSurface, WHITE, resultBack, 0)
        windowSurface.blit(result, resultBack)
        pygame.display.update()
        time.sleep(1)
    
    #draw heal results
    def drawHeal(target, h):
        result = midFont.render(str(h), True, GREEN)
        resultRect = result.get_rect()
        resultRect.centerx = target[1].centerx
        resultRect.bottom = target[1].top
        windowSurface.blit(result, resultRect)
        pygame.display.update()
        time.sleep(1)
    
    def drawAOE(targets):
        for t in targets:
            damage = midFont.render(str(t[1]), True, RED)
            damageRect = damage.get_rect()
            damageRect.centerx = t[0][1].centerx
            damageRect.bottom = t[0][1].top
            windowSurface.blit(damage, damageRect)
        pygame.display.update()
        time.sleep(1)
        
    #render text spanning multiple lines
    def renderMultiText(text, font, width):
        words = text.split(" ")
        line = ""
        surfaces = []
        for w in words:
            if font.size(line+w+" ")[0] > width:
                surfaces.append(font.render(line, True, WHITE))
                line = w + " "
            else:
                line = line + w + " "
        surfaces.append(font.render(line, True, WHITE))
        return surfaces
    
    global moving
    moving = False
    goal = None
    #Animate a unit moving
    def moveAnim(currentUnit):
        if math.fabs(currentUnit[1].left - goal[0]) < 10 and math.fabs(currentUnit[1].top - goal[1]) < 10:
            currentUnit[1].top = goal[1]
            currentUnit[1].left = goal[0]
            global moving
            moving = False
            return True
        else:
            rise,run = Utility.getSlope((currentUnit[1].left, currentUnit[1].top), goal)
            currentUnit[1].move_ip(run*7,rise*7)
            return False
    
    overlay = pygame.Surface((150,150))
    overlay.fill(BLACK)
    overlay.set_alpha(128)
    
    if type == "host":
        #Place initial units for P1
        placing = True
        toPlace = 0
        placement = ""
        while placing:
            windowSurface.fill(BLACK)
            windowSurface.blit(ground,(0,0)) 
            windowSurface.blit(overlay,(0,0))     
            drawLines()
            currImage = players[0].units[toPlace][2]
            event = pygame.event.wait()
            if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
            if event.type == MOUSEBUTTONDOWN:
                x,y = event.pos
                if x > 0 and x < 150 and y > 0 and y < 150:
                    valid = True
                    for u in players[0].units:
                        if u[1].collidepoint(x,y):
                            valid = False
                            break
                    if valid:
                        x = x - (x%50)
                        y = y - (y%50)
                        players[0].units[toPlace][1].left = x
                        players[0].units[toPlace][1].top = y
                        placement = placement+str(toPlace)+" "+str(x)+" "+str(y)+"#"
                        toPlace = toPlace + 1
                        if toPlace == len(players[0].units):
                            placing = False
            for o in obstacles:
                windowSurface.blit(rock, o)        
            for p in players:
                for u in p.units[:]:
                    pygame.draw.rect(windowSurface, p.color, u[1], 3)
                    windowSurface.blit(u[2], u[1])
                    #name = basicFont.render(u[0].name, True, WHITE)
                    hp = basicFont.render(str(u[0].hp), True, WHITE)
                    #windowSurface.blit(name, (u[1].right, u[1].top+5))
                    windowSurface.blit(hp, (u[1].left, u[1].top))
            windowSurface.blit(currImage, pygame.mouse.get_pos())
            windowSurface.blit(bigFont.render(players[0].name, True, players[0].color), (FIELDWIDTH,0))
            windowSurface.blit(midFont.render("place your units", True, players[0].color), (FIELDWIDTH,50))
            pygame.display.update()
        placement = placement.rstrip("#")
        client.send(placement)
        placement = client.recv(4096)
        placement = placement.split("#")
        for x in range(len(placement)):
            loc = placement[x].split(" ")
            players[1].units[int(loc[0])][1].x = int(loc[1])
            players[1].units[int(loc[0])][1].y = int(loc[2])
    else:
        #Place initial units for P2
        placing = True
        toPlace = 0
        placement = ""
        while placing:
            windowSurface.fill(BLACK)
            windowSurface.blit(ground,(0,0))
            windowSurface.blit(overlay,(650,450))     
            drawLines()
            currImage = players[1].units[toPlace][2]
            event = pygame.event.wait()
            if event.type == QUIT:
                    pygame.quit()
                    sys.exit()  
            if event.type == MOUSEBUTTONDOWN:
                x,y = event.pos
                if x > 650 and x < 800 and y > 450 and y < 600:
                    valid = True
                    for u in players[1].units:
                        if u[1].collidepoint(x,y):
                            valid = False
                            break
                    if valid:
                        x = x - (x%50)
                        y = y - (y%50)
                        players[1].units[toPlace][1].left = x
                        players[1].units[toPlace][1].top = y
                        placement = placement+str(toPlace)+" "+str(x)+" "+str(y)+"#"
                        toPlace = toPlace + 1
                        if toPlace == len(players[1].units):
                            placing = False
                            
            for o in obstacles:
                windowSurface.blit(rock, o)
            for p in players:
                for u in p.units[:]:
                    pygame.draw.rect(windowSurface, p.color, u[1], 3)
                    windowSurface.blit(u[2], u[1])
                    #name = basicFont.render(u[0].name, True, WHITE)
                    hp = basicFont.render(str(u[0].hp), True, WHITE)
                    #windowSurface.blit(name, (u[1].right, u[1].top+5))
                    windowSurface.blit(hp, (u[1].left, u[1].top))
            windowSurface.blit(bigFont.render(players[1].name, True, players[1].color), (FIELDWIDTH,0))
            windowSurface.blit(midFont.render("place your units", True, players[1].color), (FIELDWIDTH,50))
            windowSurface.blit(currImage, pygame.mouse.get_pos())
            pygame.display.update()
        placement = placement.rstrip("#")
        s.send(placement)
        placement = s.recv(4096)
        placement = placement.split("#")
        for x in range(len(placement)):
            loc = placement[x].split(" ")
            players[0].units[int(loc[0])][1].x = int(loc[1])
            players[0].units[int(loc[0])][1].y = int(loc[2])
    
    GameOver = False
    #Main gameplay loop
    
    if type == "host":
        myTurn = True
        myId = 0
    else:
        myTurn = False
        myId = 1
        client = s
    
    client.setblocking(0)
    while not GameOver:
        
        if not myTurn:
            try:
                action = client.recv(4096)
#                if action[0] == "move":
#                    for p in players:
#                        for u in p.units:
#                            if u[1].x == int(action[1]) and u[1].y == int(action[2]):
#                                u[1].x = int(action[3])
#                                u[1].y = int (action[4])
#                if action[0] == "attack":
#                    for p in players:
#                        for u in p.units:
#                            if u[1].x == int(action[1]) and u[1].y == int(action[2]):
#                                u[0].hp = u[0].hp - int(action[3])
                action = pickle.loads(action)
                for i in range(len(action)):
                    play = action[i]
                    for j in range(len(play.units)):
                        newUnit = play.units[j]
                        newStats = newUnit[0]
                        newRect = newUnit[1]
                        image = players[i].units[j][2]
                        newUnit = (newStats, newRect, image)
                        players[i].units[j] = newUnit 
                myTurn = True
                playerIndex = myId
                currentPlayer = players[myId]
            except socket.error:
                myTurn = False
                    
        if not moving and currentPlayer.delay == 0:
            result = currentPlayer.delayedUnit[0].skill.use(gameState,currentPlayer.delayedUnit,None)
            currentPlayer.delay = currentPlayer.delay - 1
            if result[0] == Skills.ATTACK:
                drawResult(result[1], result[2], result[3])
            playerIndex = (playerIndex + 1) % len(players)
            currentPlayer = players[playerIndex]
            ability = False
            unitSelected = False
            currentUnit = None
            unitHit = True
            continue
        elif not moving and currentPlayer.delay > 0:
            currentPlayer.delay = currentPlayer.delay - 1
            playerIndex = (playerIndex + 1) % len(players)
            currentPlayer = players[playerIndex]
            ability = False
            unitSelected = False
            currentUnit = None
            unitHit = True
            continue
        
        if moving:
            done = moveAnim(currentUnit)
            if done:
                myTurn = False
        else:        
            #for event in pygame.event.get():
            event = pygame.event.wait()
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_F1:
                    pygame.image.save(windowSurface, "screenshots/screenshot"+str(int((math.floor(time.time()))%10000))+".png")
                if event.key == K_ESCAPE:
                    break
            elif event.type == MOUSEMOTION:
                unitHovered = False
                if not unitSelected:
                    for p in players:
                        for u in p.units:
                            if u[1].collidepoint(event.pos):
                                unitHovered = True
                                hoveredUnit = u
            elif event.type == MOUSEBUTTONDOWN and myTurn:
                if event.button == 3:
                    unitSelected = False
                    ability = False
                if event.button == 1:
                    x,y = event.pos
                    x = x - (x%50)
                    y = y - (y%50)
                    
                    chosen = False
                    blocked = False
                    unitHit = False
                    
                    #check for special ability if selected
                    if ability and ground.get_rect().collidepoint(event.pos):
                        canUse = currentUnit[0].skill.canUse(gameState, currentUnit, event.pos)
                        if canUse:
                            result = currentUnit[0].skill.use(gameState, currentUnit, event.pos)
                            if result[0] == Skills.ATTACK:
                                drawResult(result[1], result[2], result[3])
                            if result[0] == Skills.DELAY:
                                currentPlayer.delay = result[1]
                                currentPlayer.delayedUnit = currentUnit
                            if result[0] == Skills.HEAL:
                                drawHeal(result[1], result[2])
                            if result[0] == Skills.AOE:
                                drawAOE(result[1])
                            playerIndex = (playerIndex + 1) % len(players)
                            currentPlayer = players[playerIndex]
                            ability = False
                            unitSelected = False
                            currentUnit = None
                            unitHit = True
                            
                            myTurn = False
                            tempPlayers = [Player(None,None), Player(None,None)]
                            for i in range(len(players)):
                                for x in range(len(players[i].units)):
                                    unit, rect, image = players[i].units[x]
                                    tempPlayers[i].units.append((unit,rect))
                                                                                
                            try:
                                message = pickle.dumps(tempPlayers)
                            except TypeError as err:
                                for foo in tempPlayers:
                                    print foo.__dict__
                                    for u in foo.units:
                                        print u, u[0].__dict__
                                print err.args[0]
                                windowSurface.blit(err.args[0], (0,0))
                                pygame.display.update()
                                time.sleep(2)
                            client.send(message)
                            continue
                        else:
                            continue
                    
                    #if player clicks on one of their units, select it
                    for u in currentPlayer.units:
                        if u[1].left == x and u[1].top == y:
                            currentUnit = u
                            border.left = x
                            border.top = y
                            unitSelected = True
                            chosen = True
                            ability = False
                            break
                    
                    #if trying to move, make sure it's not an obstacle
                    for o in obstacles:
                        if o.left == x and o.top == y:
                            blocked = True
                            break
                    
                    #if clicking skill button
                    if skillRect.collidepoint(event.pos):
                        ability = not ability
                    
                    #if a unit wasn't just chosen, but a unit is selected
                    if not chosen and unitSelected:
                        occupied = False
                        #check if clicking on an enemy's unit
                        for p in players:
                            for u in p.units:
                                if u[1].left == x and u[1].top == y:
                                    occupied = True
                                    target = u
                                    break
                        
                        #compute the manhattan distance from selected unit to clicked square        
                        distance = math.fabs(currentUnit[1].top - y) + math.fabs(currentUnit[1].left - x)
                        
                        #if the distance is within the move range and the block is free
                        if (distance // 50) <= currentUnit[0].move and not occupied and not blocked:
                            
                            #use the path search function to make sure the unit can reach his destination
                            #without passing through obstacles
                            canGo = Utility.pathSearch((currentUnit[1].left//50,currentUnit[1].top//50),
                                               (x//50,y//50), currentUnit[0].move, toCheck)
                            if canGo:
                                oldx = currentUnit[1].left
                                oldy = currentUnit[1].top
                                currentUnit[1].left = x
                                currentUnit[1].top = y
                                goal = (x,y)
                                playerIndex = (playerIndex + 1) % len(players)
                                currentPlayer = players[playerIndex]
                                unitSelected = False
                                #currentUnit = None
                                moving = True
                                myTurn = False
                                tempPlayers = copy.deepcopy(players)
                                for p in tempPlayers:
                                    for x in range(len(p.units)):
                                        unit, rect, image = p.units[x]
                                        p.units[x] = (unit,rect)
                                message = pickle.dumps(tempPlayers)
                                client.send(message)
                                currentUnit[1].left = oldx
                                currentUnit[1].top = oldy
                                #client.send("move"+" "+str(currentUnit[1].x)+" "+str(currentUnit[1].y)+" "+str(x)+" "+str(y))
                                
                        #if enemy unit in space and within attack range, attack        
                        elif occupied and (distance // 50) <= currentUnit[0].range:
                            
                            src = (currentUnit[1].centerx, currentUnit[1].centery)
                            dest = (target[1].centerx, target[1].centery)
                            sight = Utility.lineOfSight(src,dest,gameState)
                            if sight:
                                hits = defends = 0
                                for i in range(currentUnit[0].attack):
                                    if random.randint(0,1) == 0:
                                        hits = hits + 1
                                for i in range(target[0].defense):
                                    if random.randint(0,2) == 0:
                                        defends = defends + 1
                                        
                                target[0].hp = target[0].hp - max(0, hits-defends)
                                playerIndex = (playerIndex + 1) % len(players)
                                currentPlayer = players[playerIndex]
                                unitSelected = False
                                currentUnit = None
                                unitHit = True
                                drawResult(target, hits, defends)
                                myTurn = False
                                tempPlayers = copy.deepcopy(players)
                                for p in tempPlayers:
                                    for x in range(len(p.units)):
                                        unit, rect, image = p.units[x]
                                        p.units[x] = (unit,rect)
                                message = pickle.dumps(tempPlayers)
                                client.send(message)             
        #begin drawing
        windowSurface.fill(BLACK)
        windowSurface.blit(ground,(0,0))      
        drawLines()
        
        for o in obstacles:
            windowSurface.blit(rock, o)
        
        for p in players:
            for u in p.units[:]:
                if u[0].hp <= 0:
                    p.units.remove(u)
                    if len(p.units) == 0:
                        GameOver = True
                else:
                    pygame.draw.rect(windowSurface, p.color, u[1], 3)
                    windowSurface.blit(u[2], u[1])
                    #name = basicFont.render(u[0].name, True, WHITE)
                    hp = basicFont.render(str(u[0].hp), True, WHITE)
                    #windowSurface.blit(name, (u[1].right, u[1].top+5))
                    windowSurface.blit(hp, (u[1].left, u[1].top))
                    
        #Draw the unit info if a unit is selected              
        if unitSelected:
            pygame.draw.rect(windowSurface, YELLOW, border, 3)
            unitName = midFont.render(currentUnit[0].name, True, WHITE)
            unitHP = midFont.render("HP: " + str(currentUnit[0].hp), True, WHITE)
            unitMove = midFont.render("Move: " + str(currentUnit[0].move), True, WHITE)
            unitRange = midFont.render("Range: " + str(currentUnit[0].range), True, WHITE)
            unitAttack = midFont.render("Attack: " + str(currentUnit[0].attack), True, WHITE)
            unitDefense = midFont.render("Defense: " + str(currentUnit[0].defense), True, WHITE)
            
            windowSurface.blit(currentUnit[2], unitIcon)
            windowSurface.blit(unitName, (FIELDWIDTH, 150))
            windowSurface.blit(unitHP, (FIELDWIDTH, 175))
            windowSurface.blit(unitMove, (FIELDWIDTH, 200))
            windowSurface.blit(unitRange, (FIELDWIDTH, 225))
            windowSurface.blit(unitAttack, (FIELDWIDTH, 250))
            windowSurface.blit(unitDefense, (FIELDWIDTH, 275))
            
            if currentUnit[0].skill != None:
                skillName = midFont.render(currentUnit[0].skill.name, True, WHITE)
                skillDescription = renderMultiText(currentUnit[0].skill.description, basicFont, INFOWIDTH)
                windowSurface.blit(skillText, skillRect)
                windowSurface.blit(skillName, (FIELDWIDTH, 325))
                for i in range(len(skillDescription)):
                    windowSurface.blit(skillDescription[i], (FIELDWIDTH, 350 + (i*15)))
            if ability:
                pygame.draw.rect(windowSurface, YELLOW, skillRect, 3)
                if hasattr(currentUnit[0].skill, "getOutline"):
                    x,y = pygame.mouse.get_pos()
                    points = currentUnit[0].skill.getOutline(x,y)
                    pygame.draw.polygon(windowSurface, BLACK, points, 2)
                
        #Draw the unit info if a unit is selected              
        elif unitHovered:
            unitName = midFont.render(hoveredUnit[0].name, True, WHITE)
            unitHP = midFont.render("HP: " + str(hoveredUnit[0].hp), True, WHITE)
            unitMove = midFont.render("Move: " + str(hoveredUnit[0].move), True, WHITE)
            unitRange = midFont.render("Range: " + str(hoveredUnit[0].range), True, WHITE)
            unitAttack = midFont.render("Attack: " + str(hoveredUnit[0].attack), True, WHITE)
            unitDefense = midFont.render("Defense: " + str(hoveredUnit[0].defense), True, WHITE)
            
            windowSurface.blit(hoveredUnit[2], unitIcon)
            windowSurface.blit(unitName, (FIELDWIDTH, 150))
            windowSurface.blit(unitHP, (FIELDWIDTH, 175))
            windowSurface.blit(unitMove, (FIELDWIDTH, 200))
            windowSurface.blit(unitRange, (FIELDWIDTH, 225))
            windowSurface.blit(unitAttack, (FIELDWIDTH, 250))
            windowSurface.blit(unitDefense, (FIELDWIDTH, 275))
            
            if hoveredUnit[0].skill != None:
                skillName = midFont.render(hoveredUnit[0].skill.name, True, WHITE)
                skillDescription = renderMultiText(hoveredUnit[0].skill.description, basicFont, INFOWIDTH)
                
                windowSurface.blit(skillName, (FIELDWIDTH, 325))
                for i in range(len(skillDescription)):
                    windowSurface.blit(skillDescription[i], (FIELDWIDTH, 350 + (i*15)))
            
        turn = midFont.render(currentPlayer.name+"'s turn", True, currentPlayer.color) 
        windowSurface.blit(turn, infoPane)
            
        #fps = basicFont.render(str(mainClock.get_fps()), True, WHITE)    
        #windowSurface.blit(fps, (FIELDWIDTH+INFOWIDTH-fps.get_width(), FIELDHEIGHT-fps.get_height()))
            
        if GameOver:
            gg = gameOver.render("Game Over", True, BLACK, WHITE)
            ggr = gg.get_rect()
            ggr.centerx = 500
            ggr.centery = 300
            windowSurface.blit(gg,ggr)
            pygame.display.update()
            time.sleep(3)
            
        pygame.display.update()       
        mainClock.tick(20)  